import React, {Component} from "react"
import './App.css'
import Add from "./components/Add"
import List from "./components/List"
import Footer from "./components/Footer"

export default class App extends Component {
  state = {
      todoArr: [
          {id: '001', name: '抽烟', done: true},
          {id: '002', name: '喝酒', done: false},
          {id: '003', name: '打牌', done: true},
      ]
  }
  // 添加事项
  addTodo = (todoObj) => {
    const {todoArr} = this.state
    this.setState({
      todoArr: [todoObj, ...todoArr]
    })
  }
  // 勾选完成
  doneTodo = (id) => {
    const {todoArr} = this.state
    const newArr = todoArr.map((item) => {
      if(id === item.id) {
        item.done = !item.done
      }
      return item
    })
    this.setState({todoArr: newArr})
  }
  // 删除某项
  deleteTodo = (id) => {
    const {todoArr} = this.state
    const newArr = todoArr.filter(item => id !== item.id)
    this.setState({todoArr: newArr})
  }
  // 全选
  checkAll = (checked) => {
    const {todoArr} = this.state
    console.log('checked',checked)
    const newArr = todoArr.map(item => {
      item.done = checked
      return item
    })
    this.setState({todoArr: newArr})
  }
  // 清除已完成
  clearDoneFun = () => {
    const {todoArr} = this.state
    const newArr = todoArr.filter(item => !item.done)
    this.setState({todoArr: newArr})
  }
  render() {
    const {todoArr} = this.state
    return (
      <div className="todo-wrap">
        <h1>React todolist App</h1>
        <Add addTodo={this.addTodo}/>
        <List 
          todoArr={todoArr} 
          doneTodo={this.doneTodo} 
          deleteTodo={this.deleteTodo}
        />
        <Footer 
          todoArr={todoArr} 
          checkAll={this.checkAll}
          clearDoneFun={this.clearDoneFun}
        />
      </div>
    )
  }
}